package com.umeox.watch.moto.camera.view;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;


@SuppressLint("AppCompatCustomView")
public class CaptureAnimView extends ImageView {

    private static final long DURATION = 200;
    public static final int ANIM_IV_H = 800;
    public static final int ANIM_IV_W = 480;
    public static final int CAPTURE_IV_H = 80;
    public static final int CAPTURE_IV_W = 48;
    private AnimationListener mAnimationListener;
    AnimatorSet mAnimSet = new AnimatorSet();

   public interface AnimationListener {
        void onAnimationEnd();
    }

    public CaptureAnimView(Context context) {
        this(context, null);
    }

    public CaptureAnimView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CaptureAnimView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }


    public void startAnimation() {
        int h = CAPTURE_IV_H;
        int w = CAPTURE_IV_W;
        final float scaleX2 = w * 1.0f / ANIM_IV_W;
        final float scaleY2 = h * 1.0f / ANIM_IV_H;
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(this, "scaleX", 1, scaleX2);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(this, "scaleY", 1, scaleY2);
        scaleX.setDuration(DURATION);
        scaleY.setDuration(DURATION);
        ObjectAnimator animator = ObjectAnimator.ofFloat(this, "translationX", 0, 0);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(this, "translationY", 0, 120-h/2.0f-12);
        animator.setDuration(DURATION);
        animator2.setDuration(DURATION);
        mAnimSet.playTogether(scaleX,scaleY,animator2);
        mAnimSet.addListener(listener);
        mAnimSet.start();
    }



    public void setAnimationListener(AnimationListener animationListener) {
        mAnimationListener = animationListener;
    }

    Animator.AnimatorListener listener = new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {

        }

        @Override
        public void onAnimationEnd(Animator animation) {
            if (mAnimationListener != null) {
                mAnimationListener.onAnimationEnd();
            }
        }

        @Override
        public void onAnimationCancel(Animator animation) {

        }

        @Override
        public void onAnimationRepeat(Animator animation) {

        }
    };

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        post(() -> setImageDrawable(null));
    }
}
